<template>
  <div>
    <h1>基础信息</h1>
    <div style="margin-top: 20px; width: 900px">
      <el-form :model="form" :inline="true">
        <el-form-item label="工单编号">
          <el-input
            v-model="form.productionordersNo"
            autocomplete="off"
            style="width: 180px; height: 30px"
            :readonly="form.autoGenerate"
            clearable
            @click.native="handleCodeClick"
          />
          <template slot="prepend">R</template>
          <el-switch
            width="40"
            v-model="form.autoGenerate"
            active-text="自动生成"
            active-color="#67C23A"
            @change="handleSwitchChange"
          />
        </el-form-item>
        <el-form-item label="工单名称" style="margin-left: 30px">
          <el-input
            v-model="form.productionordersName"
            style="width: 220px; margin-left: 10px"
          />
        </el-form-item>
        <el-form-item label="关联生产单号">
          <el-input
            v-model="workOrder.workOrderCoding"
            style="width: 220px; margin-left: 10px"
            readonly
          >
            <template #append>
              <el-button icon="Search" @click="handleWorkOrderChange" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="销售订单号">
          <el-input v-model="workOrder.orderNumber" readonly />
        </el-form-item>
        <el-form-item label="工单主题">
          <el-select
            v-model="form.topic"
            placeholder="请选择工单主题"
            style="width: 220px; margin-left: 10px"
          >
            <el-option value="1" label="天马幸亏研发计划" />
            <el-option value="2" label="一拖再拖创新工程" />
            <el-option value="3" label="瞬间消失方案" />
            <el-option value="4" label="能拖就拖上线项目" />
            <el-option value="5" label="预算方案" />
            <el-option value="6" label="不靠谱创新功能" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="form.ProductionordersStatus"
            placeholder="请选择工单主题"
            style="width: 220px; margin-left: 10px"
          >
            <el-option :value="null" label="请选择" />
            <el-option :value="false" label="未下单" />
            <el-option :value="true" label="已下单" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单日期">
          <el-date-picker
            v-model="form.productionordersTime"
            placeholder="请选择工单日期"
          />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="form.head" />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input v-model="form.department" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            style="width: 800px; margin-left: 10px"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            maxlength="100"
          />
        </el-form-item>
      </el-form>
    </div>

    <h1 style="margin-top: 20px">生产物品</h1>
    <div style="margin-top: 20px; width: 900px">
      <el-form :model="form" :inline="true">
        <el-form-item label="物品名称">
          <el-input v-model="model.materialname" readonly />
        </el-form-item>
        <el-form-item label="物品编号">
          <el-input
            v-model="model.materialnumber"
            style="width: 220px; margin-left: 10px"
            readonly
          >
            <template #append>
              <el-button icon="Search" @click="handlerMeterial" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="model.specification" readonly />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="model.unit" readonly />
        </el-form-item>
        <el-form-item label="物品类别">
          <el-input v-model="model.materialproduct" readonly />
        </el-form-item>
        <el-form-item label="物品分类">
          <el-input v-model="model.sort" readonly />
        </el-form-item>
        <el-form-item label="计划开始时间">
          <el-date-picker
            v-model="form.planStartTime"
            placeholder="请选择工单日期"
          />
        </el-form-item>
        <el-form-item label="计划结束时间">
          <el-date-picker
            v-model="form.planEndTime"
            placeholder="请选择工单日期"
          />
        </el-form-item>
        <el-form-item label="计划产量">
          <el-input v-model="form.yield" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 显示工艺流程 -->
    <div style="margin-top: 20px">
      <h1>工艺流程</h1>
      <el-button type="primary" size="small" @click="addProcess"
        >添加</el-button
      >
      <el-button type="danger" size="small" @click="removeSelectedProcess"
        >移除</el-button
      >
      <el-table
        @selection-change="handleSelection"
        :data="procee"
        style="width: 100%; margin-top: 10px"
      >
        <!--   <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
          
            <el-radio
              v-model="selectedSupplierProcessId"
              :label="row.processID"
              @change="handleArriprocessSelect(row)"
            ></el-radio>
          </template>
        </el-table-column> -->
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="processNo" label="工序编码" />
        <el-table-column prop="processName" label="工序名称" />
        <el-table-column prop="productionordersNo" label="工序流程编号" />
        <el-table-column prop="processdescris" label="备注" />
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="mini" @click="moveUpProcess(scope.$index)"
              >上移</el-button
            >
            <el-button size="mini" @click="moveDownProcess(scope.$index)"
              >下移</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="removeProcess(scope.$index)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-form-item>
      <el-button type="primary" @click="save">提交</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </div>

  <!-- 显示生产单号列表 -->

  <div>
    <el-dialog
      v-model="Eject.dialogFormVisible"
      title="生产单号列表"
      width="1000"
    >
      <el-table :data="worder" style="width: 100%; margin-top: 10px">
        <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
            <!-- 修复2: 使用唯一标识符作为radio的value -->
            <el-radio
              v-model="selectedSupplierArrMateId"
              :label="row.workOrderId"
              @change="handleArrivalnoticematerSelect(row)"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="workOrderCoding" label="工单编码" />
        <el-table-column prop="workOrderName" label="工单名称" />
        <el-table-column prop="workOrderType" label="工单类型" />
        <el-table-column prop="workorderSource" label="工单来源" />
        <el-table-column prop="orderNumber" label="订单编号" />
        <el-table-column prop="productNumber" label=" 产品编号" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="specifications" label="规格型号" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="workOrderNum" label="工单数量" />
        <el-table-column prop="adjustQuantity" label="调整数量" />
        <el-table-column prop="quantityProduced" label="已生产数量" />
        <el-table-column prop="lotNumber" label="批次号" />
        <el-table-column prop="customerCode" label="客户编码" />
        <el-table-column prop="customerNamwe" label="客户名称" />
        <el-table-column prop="requestDate" label="入库日期" width="180">
          <template #default="scope">
            {{ scope.row.requestDate.substring(0, 10) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>

  <!-- 生产物品列表 -->
  <div>
    <el-dialog
      v-model="Eject.dialogFormMaterVisible"
      title="生产物品列表"
      width="1000"
    >
      <el-table :data="meter" style="width: 100%; margin-top: 10px">
        <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedSupplierMaterArrMateId"
              :label="row.mId"
              @change="handleaterSelect(row)"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="materialnumber" label="物料编码" />
        <el-table-column prop="materialname" label="物料名称" />
        <el-table-column prop="specification" label="规格型号" />
        <el-table-column prop="unit" label="单位">
          <template #default="scope">
            <el-text v-if="scope.row.unit == 1">个</el-text>
            <el-text v-else-if="scope.row.unit == 2">克</el-text>
            <el-text v-else-if="scope.row.unit == 3">千克</el-text>
            <el-text v-else-if="scope.row.unit == 4">吨</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="materialproduct" label="物料/产品">
          <template #default="scope">
            <el-text v-if="scope.row.materialproduct == 1">物料</el-text>
            <el-text v-else>产品</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="所属分类">
          <template #default="scope">
            <el-text v-if="scope.row.sort == 1">成品</el-text>
            <el-text v-else-if="scope.row.sort == 2">半成品</el-text>
            <el-text v-else-if="scope.row.sort == 3">废料</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="isEnable" label="是否启用">
          <template #default="scope">
            <el-text v-if="scope.row.isEnable === false" type="primary"
              >否</el-text
            >
            <el-text v-else type="primary">是</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="safetystock" label="设置安全库存">
          <template #default="scope">
            <el-text v-if="scope.row.safetystock === false" type="primary"
              >否</el-text
            >
            <el-text v-else type="primary">是</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="sTime" label="创建时间" width="150">
          <template #default="scope">
            {{ new Date(scope.row.sTime).toLocaleString() }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { readaxios, writeaxios } from "@/https/axioshttps";
import axios from "axios";

const selectedSupplierArrMateId = ref<number | null>(null);
const selectedSupplierMaterArrMateId = ref<number | null>(null);
const selectedSupplierProcessId = ref<number | null>(null);
const Eject = reactive({
  dialogFormVisible: false,
  dialogFormMaterVisible: false,
  formLabelWidth: "120px",

  Isture: true,
});

const router = useRouter();
const route = useRoute();
// 获取生产工单列表字段
const form = reactive({
  productionordersId: 0,
  productionordersNo: "",
  productionordersName: "",
  topic: "",
  head: "",
  department: "",
  ProductionordersStatus: null,
  planStartTime: "",
  planEndTime: "",
  yield: "",
  remark: "",
  isDelete: false,
  mId: 0,
  workOrderId: 0,
  productionordersTime: new Date(),
  processID: 0,
  processIDs: [],
  autoGenerate: false,
});
const model = reactive({
  materialnumber: "",
  materialname: "",
  specification: "",
  unit: "",
  materialproduct: "",
  sort: "",
});

const workOrder = reactive({
  workOrderId: 0,
  workOrderCoding: "",
  orderNumber: "",
});
// 生成工单编号（GYLX+时间戳）
const generateCode = () => {
  const timestamp = new Date()
    .toISOString()
    .replace(/[-:TZ]/g, "")
    .substring(0, 14); // 获取精确到毫秒的时间戳
  form.productionordersNo = `SCDH${timestamp}`;
};

const handleSwitchChange = (val: boolean) => {
  form.autoGenerate = val;
  if (val) {
    generateCode(); // 开启自动生成时立即生成
  } else {
    form.productionordersNo = ""; // 关闭时清空编号
  }
};

const handleCodeClick = () => {
  if (form.autoGenerate) {
    generateCode(); // 点击输入框时重新生成
  }
};

const handleWorkOrderChange = () => {
  Eject.dialogFormVisible = true;
  workOrderInfo();
};
const worder = ref([]);
const workOrderInfo = () => {
  axios
    .get("http://localhost:5056/api/Productionorderss/GetProductionorderss")
    .then((res) => {
      console.log(res.data.data);
      worder.value = res.data.data;
    });
};

const handleArrivalnoticematerSelect = (row: any) => {
  form.workOrderId = row.workOrderId;
  workOrder.workOrderCoding = row.workOrderCoding;
  workOrder.orderNumber = row.orderNumber;
  // 关闭对话框前重置选择状态
  setTimeout(() => {
    Eject.dialogFormVisible = false;
    selectedSupplierArrMateId.value = null; // 清除选中状态
  }, 100);
};

// 生产物品

const handlerMeterial = () => {
  Eject.dialogFormMaterVisible = true;
  getMeter();
};

const meter = ref([]);
const getMeter = () => {
  axios
    .get(
      "http://localhost:5056/api/Productionorderss/GetProductionorderssMater"
    )
    .then((res) => {

      meter.value = res.data.data;
    });
};

const handleaterSelect = (row: any) => {
  form.mId = row.mId;

  model.materialnumber = row.materialnumber;
  model.materialname = row.materialname;
  model.specification = row.specification;
  model.unit = row.unit;
  model.materialproduct = row.materialproduct;
  model.sort = row.sort;

  // 关闭对话框前重置选择状态
  setTimeout(() => {
    Eject.dialogFormMaterVisible = false;
    selectedSupplierArrMateId.value = null; // 清除选中状态
  }, 100);
};

// 显示工序
const page = reactive({
  PageIndex: 1,
  PageSize: 0,
  totalCount: 0,
  totalPage: 0,
});
/* onMounted(() => {
  getproceess();
}); */
const procee = ref([]);

const getproceess = () => {
  axios
    .get("http://localhost:5056/api/Productionorderss/GetwoekderProess", {
      params: page,
    })
    .then((res) => {
      procee.value = res.data.data;
      page.totalCount = res.data.totalCount;
      page.totalPage = res.data.totalPage;
    });
};


// 添加工序
const addProcess = () => {
  page.PageSize = page.PageSize + 1;
  // console.log(page.PageSize,'555');
  getproceess();
};

// 移除选中的工序
const removeSelectedProcess = () => {
  page.PageSize = page.PageSize - 1;
  getproceess();
};
// 上移工序
const moveUpProcess = (index: number) => {
  // alert(index);
  if (index != 0) {
    const temp = procee.value[index];
    alert(temp);
    procee.value[index] = procee.value[index - 1];
    procee.value[index - 1] = temp;
  }
};

// 下移工序
const moveDownProcess = (index: number) => {
  if (index < procee.value.length - 1) {
    const temp = procee.value[index];
    procee.value[index] = procee.value[index + 1];
    procee.value[index + 1] = temp;
  }
};

// 移除指定工序
const removeProcess = (index: number) => {
  page.PageSize = page.PageSize - 1;
  procee.value.splice(index, 1);
};

const selectedProcessIds = ref([]);

const zhuanhuan = () => {
  form.processIDs = selectedProcessIds.value;
  console.log(form.processIDs, "4444");
};
// 处理表格选择变化事件
const handleSelection = (selection: any) => {
  console.log(selection, "666");
  selectedProcessIds.value = selection.map((item) => item.processID); // 假设工序对象有 id 属性，根据实际情况修改
  zhuanhuan();
  console.log(selectedProcessIds.value, "selectedProcessIds:");
};


// 添加生产工单信息
const save = () => {
  const payload = {
    productionordersId: form.productionordersId,
    productionordersNo: form.productionordersNo,
    productionordersName: form.productionordersName,
    topic: form.topic,
    head: form.head,
    department: form.department,
    ProductionordersStatus: form.ProductionordersStatus,
    planStartTime: form.planStartTime,
    planEndTime: form.planEndTime,
    yield: form.yield,
    remark: form.remark,
    isDelete: form.isDelete,
    mId: form.mId,
    workOrderId: form.workOrderId,
    productionordersTime: form.productionordersTime,
    processID: form.processID,
    processIDs: form.processIDs,
  };

  axios
    .post("http://localhost:5057/api/Productionorderss/Handle", payload)
    .then((res) => {
      if (res.data.code === 100) {
        console.log(res.data.data, "添加成功22222");
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        router.push("/GetProductionwork");
      } else {
        ElMessage({
          message: "添加失败",
          type: "error",
        });
      }
    });
};
</script>

<style scoped>
</style>